package com.swt.draw.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.swt.draw.entity.Department;
import java.util.List;

/**
 * @ClassName
 * @Description 部门列表转树形结构
 * @Author Administrator
 * @Date 2019/8/25 0025 8:41
 * @Version 1.0
 **/
public class DepartmentList2Tree {

    /*部门列表转树形结构*/
    public static JSONArray toTree(List<Department> departments) {
        return listToTree(JSONArray.parseArray(JSONObject.toJSONString(departments, SerializerFeature.DisableCircularReferenceDetect)),"departmentNo","departmentParentNo","childs");
    }

    /**
     * @Author ZPF
     * @Description JSONArray转树形结构JSONArray
     * @Date 10:35 2019/8/25 0025
     * @Param [arr, id, pid, child]
     * @return com.alibaba.fastjson.JSONArray
     **/
    public static JSONArray listToTree(JSONArray arr, String id, String pid, String child) {
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式，key为数组中的id
        for (int i = 0; i < arr.size(); i++) {
            JSONObject json = (JSONObject) arr.get(i);
            hash.put(json.getString(id), json);
        }
        //遍历结果集
        for (int j = 0; j < arr.size(); j++) {
            //单条记录
            JSONObject aVal = (JSONObject) arr.get(j);
            //在hash中取出key为单条记录中pid的值
            String pidStr = "";
            Object pidObj = aVal.get(pid);
            if (aVal.get(pid) != null) {
                pidStr = aVal.get(pid).toString();
            }
            JSONObject hashVP = (JSONObject) hash.get(pidStr);
            //如果记录的pid存在，则说明它有父节点，将她添加到孩子节点的集合中
            if (hashVP != null) {
                //检查是否有child属性
                if (hashVP.get(child) != null) {
                    JSONArray ch = (JSONArray) hashVP.get(child);
                    ch.add(aVal);
                    hashVP.put(child, ch);
                } else {
                    JSONArray ch = new JSONArray();
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }
            } else {
                r.add(aVal);
            }
        }
        return r;
    }

}
